package com.liujunwen.demo.controller;

import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.env.Environment;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping(value = "consumer")
public class ConsumerController {
    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Autowired
    private Environment env;

    @Value("${mq.queue.name}")
    public String queue;

    @Value("${mq.routing.key.name}")
    public String routingKey;

    @Value("${mq.exchange.name}")
    public String exchange;

    @RequestMapping(value = "/receive", method = RequestMethod.GET)
    public String receive() {
        try {
            rabbitTemplate.setMessageConverter(new Jackson2JsonMessageConverter());
            rabbitTemplate.setQueue(queue);
            rabbitTemplate.setExchange(exchange);
            rabbitTemplate.setRoutingKey(routingKey);
            Message receive = rabbitTemplate.receive();
            if (receive != null) {
                String info = new String(receive.getBody(), "utf-8");
                return info;
            }
            return "没有数据";

        } catch (Exception e) {
            e.printStackTrace();
            return e.toString();
        }
    }
}
